<!--
  @Description:责任部门接收人 (责任部门派单)
  @Author:zqy
  @Date:2022-05-23 10:27:13
  @Last Modified by:zqy
  @Last Modified time:2022-05-23 10:27:13
-->
<template>
  <div class="departDispatchPage">
    <Button type="primary" :disabled="!buttonAuth" @click="clickHandle">{{ text }}</Button>
    <el-dialog
      v-if="visible"
      :visible.sync="visible"
      destroy-on-close
      width="90%"
      :close-on-click-modal="false"
      :title="title"
      :append-to-body="true"
      @open="openHandle"
      @close="closeDialog"
    >
      <div class="contentBody">
        <!-- <search-form ref="refSearch" :search-config="searchConfig" :copyable="false" label-width="110" @clear="handleClearSearch" @search="handleSearch" @edit-change="handleSearchEditChange" /> -->
        <FormContainer :column="4">
          <el-form
            ref="searchForm"
            :model="formData"
            :rules="formRules"
            label-width="70px"
          >
            <el-form-item prop="dept" label="责任部门">
              <CustomDictSelect
                placeholder="请选择"
                dict-type-code="RESPONSIBLE_DEPARTMENT"
                bind-name="dictName"
                bind-value="dictCode"
                collapse-tags
                :multiple="false"
                filterable
                :echo-value.sync="formData.dept"
                @on-change="deptChannelHandle"
              ></CustomDictSelect>
            </el-form-item>
            <el-form-item prop="qupOrganization" label="QUP组织">
              <SearchSelectPicker
                :url="`/call-center/api/v1/staffInfo/remoteOrg/${formData.dept}/page`"
                placeholder="请选择"
                lable-name="orgName"
                value-name="orgCode"
                :must-pid="true"
                :parent-id="formData.dept"
                :value.sync="formData.qupOrganization"
                filterable
                @selectChange="qupOrganizationChange"
              ></SearchSelectPicker>
            </el-form-item>
            <el-form-item prop="receiver" label="用户">
              <SearchSelectPicker
                :url="`/call-center/api/v1/staffInfo/user/org/${formData.qupOrganization}`"
                placeholder="请选择"
                lable-name="userName"
                value-name="account"
                :must-pid="true"
                :parent-id="formData.qupOrganization"
                :value.sync="formData.receiver"
                filterable
              ></SearchSelectPicker>
            </el-form-item>
            <el-form-item prop="receiverPhone" label="联系电话" hidden>
              <el-input v-model.trim="formData.receiverPhone" placeholder="请输入联系电话" clearable />
            </el-form-item>
            <el-form-item prop="platformCode" label="电商平台">
              <SearchSelectPicker
                url="/select-service/api/v1/eco/platform/page"
                placeholder="请选择"
                lable-name="name"
                value-name="code"
                :value.sync="formData.platformCode"
                filterable
                @selectChange="platformCodeChangeHandle"
              ></SearchSelectPicker>
            </el-form-item>
            <el-form-item prop="storeCode" label="电商店铺">
              <SearchSelectPicker
                url="/select-service/api/v1/eco/shop/page"
                placeholder="请选择"
                lable-name="name"
                value-name="code"
                :value.sync="formData.storeCode"
                filterable
                :must-pid="true"
                :parent-id="formData.platformCode"
                :params="{
                  type:0,
                  query:{ platformCode:{ value:formData.platformCode,operator:'=' } }
                }"
              ></SearchSelectPicker>
            </el-form-item>
            <el-form-item prop="postCode" label="岗位">
              <CustomDictSelect
                placeholder="请选择"
                dict-type-code="DEPT_POST_CODE"
                bind-name="dictName"
                bind-value="dictCode"
                collapse-tags
                :multiple="false"
                filterable
                :echo-value.sync="formData.postCode"
              ></CustomDictSelect>
            </el-form-item>
            <el-form-item align="right" label-width="0px" show more style="white-space: nowrap;">
              <Button @click="resetSearch('searchForm')">重置</Button>
              <Button type="primary" enter @click="querySearch('searchForm')">查询</Button>
            </el-form-item>
          </el-form>
        </FormContainer>
        <table-box
          ref="refTable"
          table-size="small"
          :table-config="tableConfig"
          :other-filters="otherFilters"
          :table-height="400"
          no-request
          :show-index="false"
          :show-selection="true"
          :show-custom-setting="false"
          :selected-arry.sync="tableSelected"
          :table-sortable="false"
          @selection-change="handleselectionChange"
        />
        <!-- @row-click="handleRowClick" -->
      </div>
      <div style="text-align: right;margin-top:10px">
        <Button @click="closeDialog">取消</Button>
        <Button type="primary" :loading="isLoading" @click="submitHandle">确定</Button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Button from '@/components/Button'
import { ArrayFormat } from '@/utils/params-format'
import { deepCopy, isEmpty } from '@/utils/'
import FormContainer from '@/components/FormContainer'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import CustomDictSelect from '@/components/CustomDictSelect'
export default {
  name: 'DepartDispatchOrder',
  components: {
    Button,
    FormContainer,
    SearchSelectPicker,
    CustomDictSelect
  },
  props: {
    text: {
      type: String,
      default: '责任部门'
    },
    title: {
      type: String,
      default: '责任部门派单'
    },
    source: {
      type: String,
      default: 'dispatch'
    }, // cc 抄送
    enableOpen: {
      type: Function,
      default: () => Promise.reject(),
      require: true
    },
    buttonAuth: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isLoading: false,
      visible: false,
      formData: {
        dept: '',
        qupOrganization: '',
        receiver: '',
        receiverPhone: '',
        platformCode: '',
        storeCode: '',
        postCode: '',
        state: ''
      },
      formRules: {

      },
      searchConfig: [
        {
          label: '责任部门', prop: 'dept', type: 'select', value: '',
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/RESPONSIBLE_DEPARTMENT`,
            defaultProps: { label: 'dictName', value: 'dictCode' },
            paramsRaw: {
              appCode: 'call-center',
              domainCode: 'marketing'
            }
          }
        },
        {
          label: 'QUP组织', prop: 'qupOrganization', type: 'select', value: '',
          config: {
            selectData: []
          }
        },
        {
          label: '用户', prop: 'receiver', type: 'select', value: '',
          config: {
            selectData: []
          }
        },
        { label: '联系电话', prop: 'receiverPhone', type: 'text', value: '' },
        { label: '电商平台', prop: 'platformCode', type: 'dialog', value: '',
          config: {
            multiple: false,
            defaultProps: { label: 'name', value: 'code' }
          },
          dialogConfig: {
            title: '电商平台',
            interfacePath: '/select-service/api/v1/eco/platform/page',
            setting: [{ prop: 'code', title: '编码', width: 120 }, { prop: 'name', title: '名称', width: 250 }]
          }
        },
        {
          label: '电商店铺', prop: 'storeCode', type: 'dialog', value: '',
          config: {
            multiple: false,
            defaultProps: { label: 'name', value: 'code' }
          },
          dialogConfig: {
            title: '电商店铺',
            interfacePath: '/select-service/api/v1/eco/shop/page',
            setting: [{ prop: 'code', title: '编码', width: 120 }, { prop: 'name', title: '名称', width: 250 }]
          }
        },
        {
          label: '岗位', prop: 'postCode', type: 'select', value: '',
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/DEPT_POST_CODE`,
            defaultProps: { label: 'dictName', value: 'dictCode' },
            paramsRaw: {
              appCode: 'call-center',
              domainCode: 'marketing'
            }
          }
        }
        /* {
          label: '启用状态', prop: 'state', type: 'select', value: '1',
          config: {
            selectData: [
              { label: '启用', value: '1' },
              { label: '停用', value: '0' }
            ]
          }
        } */
      ],
      otherFilters: [], // 表格额外查询条件
      otherRaws: {},
      tableSelected: [], // 选择列
      tableConfig: {
        interfacePath: `/call-center/api/v2/workOrderDeptReceiver/dispatchPage`,
        tabIndex: 20,
        hideFuncBar: true,
        // sort: 'createTime',
        order: 'desc',
        setting: [
          {
            prop: 'deptName',
            label: '责任部门',
            minWidth: 150
          },
          {
            prop: 'qupOrganizationName',
            label: 'QUP组织',
            minWidth: 150
          },
          {
            prop: 'receiver',
            label: '用户',
            minWidth: 150,
            formatData: ({ receiver, receiverName }) => {
              return ` ${receiverName}(${receiver})`
            }
          },
          {
            prop: 'receiverPhone',
            label: '联系电话',
            minWidth: 150
          },
          {
            prop: 'platformName',
            label: '电商平台',
            minWidth: 150,
            formatData: ({ platformList, platformName }) => {
              if (platformList) {
                const name = platformList.map(v => v.platformName)
                return name.join(',')
              } else {
                return platformName
              }
            }
          },
          {
            prop: 'storeName',
            label: '电商店铺',
            minWidth: 150,
            formatData: ({ platformStoreList, storeName }) => {
              if (platformStoreList) {
                const name = platformStoreList.map(v => v.storeName)
                return name.join(',')
              } else {
                return storeName
              }
            }
          },
          {
            prop: 'postName',
            label: '岗位',
            minWidth: 150
          },
          {
            prop: 'remark',
            label: '备注',
            minWidth: 150
          },
          {
            prop: 'receiverCount', // TODO:字段暂缺
            label: '今日工单接收量',
            width: 140,
            formatData: ({ receiverCount }) => {
              return receiverCount || 0
            }
          },
          {
            prop: 'state',
            label: '启用状态',
            width: 100,
            formatData: ({ state }) => {
              return Number(state || 0) === 1 ? '启用' : '停用'
            }
          }
        ]
      }
    }
  },
  computed: {

  },
  methods: {
    openHandle() {

    },
    clickHandle() {
      this.enableOpen().then(() => {
        this.visible = true
      })
    },
    closeDialog() {
      this.visible = false
      this.tableSelected = []
    },
    handleRowClick({ row }) {
      this.$refs.refTable.clearSelection()
      this.$nextTick(() => {
        this.$refs.refTable.toggleRowSelection(row, true)
      })
    },
    handleselectionChange(val) {
      this.tableSelected = val
    },
    // 搜索项联动
    handleSearchEditChange({ prop, value }) {
      if (prop === 'dept') {
        // 切换责任部门
        this.setQupOrgConfig(value)
      } else if (prop === 'qupOrganization') {
        // 切换组织
        this.setUerConfig(value)
      } else if (prop === 'platformCode') {
        // 切换平台时，更新店铺选项
        const val = value && value.length ? value[0].value || '' : ''
        this.setStoreConfig(val)
      } else if (prop === 'storeCode') {
        // 切换门店,设置默认平台数据
        const tmp = value && value.length ? value[0] : ''
        const platformVal = []
        let code = this.$refs.refSearch.searchData['platformCode'] || ''
        if (tmp && tmp.platformCode && tmp.platformName && tmp.platformCode !== code) {
          platformVal.push({
            code: tmp.platformCode,
            name: tmp.platformName
          })
          code = tmp && tmp.platformCode
          const configItem = this.searchConfig.find(v => v.prop === 'platformCode')
          this.$set(configItem, 'value', platformVal)
          this.$refs.refSearch.updateValue('platformCode', code)
          this.setStoreConfig(code, true)
        }
      }
    },
    // 设置QUP组织查询配置
    setQupOrgConfig(value) {
      let config = {
        remote: false,
        remoteUrl: '',
        selectData: []
      }
      if (value) {
        config = {
          remote: true,
          requestMethod: 'post',
          remoteUrl: `/call-center/api/v1/staffInfo/remoteOrg/${value}/page`,
          defaultProps: { label: 'orgName', value: 'orgCode' }
        }
      }
      this.$refs.refSearch.initSelectData('qupOrganization', config)
      this.$refs.refSearch.updateValue('qupOrganization', '')
    },
    // 设置用户查询配置
    setUerConfig(value) {
      let config = {
        remote: false,
        remoteUrl: '',
        selectData: []
      }
      if (value) {
        config = {
          remote: true,
          requestMethod: 'post',
          remoteUrl: `/call-center/api/v1/staffInfo/user/org/${value}`,
          defaultProps: { label: 'userName', value: 'account' }
        }
      }
      this.$refs.refSearch.initSelectData('receiver', config)
      this.$refs.refSearch.updateValue('receiver', '')
    },
    // 设置店铺查询配置
    setStoreConfig(platformCode, onlyFilter = false) {
      const filtersRaw = []
      if (platformCode) {
        filtersRaw.push({ id: 'platformCode', property: 'platformCode', operator: '=', value: `${platformCode}` })
      }
      const configItem = this.searchConfig.find(v => v.prop === 'storeCode')
      this.$set(configItem.dialogConfig, 'filtersRaw', filtersRaw)
      if (onlyFilter) return
      this.$set(configItem, 'value', [])
      this.$refs.refSearch.updateValue('storeCode', '')
    },
    // 清空查询条件
    handleClearSearch() {
      this.setQupOrgConfig()
      this.setUerConfig()
      this.setStoreConfig()
    },
    // 搜索
    handleSearch(params) {
      this.otherFilters = params.filtersRaw || []
      this.otherRaws = params.paramsRaw || {}
      this.refreshTable(true)
    },
    // 刷新主表
    refreshTable(isInit) {
      this.$nextTick(() => {
        this.$refs.refTable && this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
        this.tableSelected = []
      })
    },
    submitHandle() {
      if (this.tableSelected.length === 0) {
        this.$message.warning('请至少选择1位接收人')
        return
      }
      this.$msgbox({
        title: `确认${this.source === 'cc' ? '抄送' : '派单'}`,
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        message: `该工单确定要${this.source === 'cc' ? '抄送' : '派单'}给当前所选接收人吗？`
      }).then(async() => {
        // const ids = this.tableSelected.map(v => v.id)
        this.$emit('select-change', this.tableSelected)
      })
    },
    // 重置表单
    resetSearch(formName) {
      Object.keys(this.formData).forEach(k => {
        this.$set(this.formData, k, '')
      })
      this.$refs[formName].resetFields()
    },
    /**
     * 查询表单
     */
    querySearch(formName, type, onPage) {
      const v = Object.keys(this.formData).some(key => {
        return !isEmpty(this.formData[key])
      })
      if (!v) {
        this.$message({
          title: '提示',
          message: '至少填写或选择一项查询条件',
          type: 'warning'
        })
        return
      }
      this.$refs[formName].validate().then(() => {
        const formData = deepCopy(this.formData)
        this.otherFilters = [...ArrayFormat(formData, {
          dept: '=', qupOrganization: '=', receiver: '=',
          receiverPhone: '=', platformCode: '=', storeCode: '=', postCode: '=',
          state: '='
        })]
        this.refreshTable(true)
      })
    },
    // 责任部门选择变更
    deptChannelHandle(dict) {
      this.$set(this.formData, 'qupOrganization', '')
      this.qupOrganizationChange('')
    },
    // qup组织选择变更
    qupOrganizationChange(org) {
      // const orgCode = org.orgCode || ''
      this.$set(this.formData, 'receiver', '')
    },
    // 电商平台切换
    platformCodeChangeHandle(platform) {
      this.$set(this.formData, 'storeCode', '')
    }

  }
}
</script>
<style lang="scss" scoped>

</style>
